/**
 * 权限路由过滤 Store
 * 参考 xz-crm-b 项目实现
 */
import { defineStore } from "pinia";
import type { RouteRecordRaw } from "vue-router";

/**
 * 检查路由是否有权限访问
 */
function hasPermission(
  route: RouteRecordRaw,
  authorityCodeList: string[]
): boolean {
  const meta = route.meta as any;
  const permission = meta?.permission;

  if (!permission) {
    return true;
  }

  const permCode =
    typeof permission === "string" ? permission : permission.code;

  if (!permCode || authorityCodeList.includes(permCode)) {
    return true;
  }

  return false;
}

/**
 * 过滤异步路由
 * @param routes 路由配置
 * @param authorityCodeList 权限码列表
 * @param moduleResourceCodes 已开通的模块资源编码
 * @param notActivatedModule 是否为未开通模块
 */
export function filterAsyncRouter(
  routes: RouteRecordRaw[],
  authorityCodeList: string[],
  moduleResourceCodes: string[],
  notActivatedModule?: boolean
): any[] {
  return routes.map((route) => {
    let { children, meta = {} } = route;
    const routeMeta = meta as any;

    notActivatedModule = routeMeta?.notActivatedModule || notActivatedModule;

    // 递归处理子路由
    if (children && children.length > 0) {
      children = filterAsyncRouter(
        children,
        authorityCodeList,
        moduleResourceCodes,
        notActivatedModule
      ) as any;
    }

    // 计算可见子路由数量
    const childrenLen =
      children?.filter((it) => !(it.meta as any)?.hide)?.length || 0;

    if (childrenLen > 0) {
      return {
        ...route,
        children,
      };
    }

    // 检查权限
    if (!hasPermission(route, authorityCodeList)) {
      // A类账号、B类账号没有开通 && 模块开通时 展示403
      const showNoAuth = authorityCodeList?.length && !notActivatedModule;

      return {
        ...route,
        children,
        meta: {
          ...routeMeta,
          hide: true,
          activeHideBreadCrumb: true, // 动态隐藏面包屑
        },
        // 1. A类账号、B类账号没有开通时，展示404
        // 2. 模块没有开通时展示404
        component: showNoAuth
          ? () => import("@/views/common/NoPermission.vue")
          : () => import("@/views/common/404.vue"),
      };
    }

    return {
      ...route,
      children,
    };
  });
}

/**
 * 格式化路由模块开通状态
 */
export function formatRouterModuleOpenStatus(
  routers: RouteRecordRaw[],
  moduleResourceCodes: string[]
): RouteRecordRaw[] {
  return routers.map((route) => {
    const meta = route.meta as any;

    return {
      ...route,
      meta: {
        ...meta,
        code: meta?.permission?.code || meta?.code || "",
        // 模块未开通
        notActivatedModule: meta?.paidItemCode
          ? !moduleResourceCodes?.includes(meta.paidItemCode)
          : false,
      },
    };
  });
}

export const usePermissionStore = defineStore("permission", {
  state: () => ({
    /** 所有路由（包括静态路由和动态路由） */
    routers: [] as RouteRecordRaw[],
    /** 动态添加的路由 */
    addRouters: [] as RouteRecordRaw[],
  }),

  actions: {
    /**
     * 设置路由
     */
    setRouters(routes: RouteRecordRaw[]) {
      this.addRouters = routes;
      this.routers = [...routes];
    },

    /**
     * 更新应用路由
     */
    updateAppRouter(routes: RouteRecordRaw[]) {
      return new Promise<string>((resolve) => {
        // 兼容切换组织、刷新页面时，页面标题先展示了404
        this.setRouters(
          routes.concat([
            {
              path: "/:pathMatch(.*)*",
              meta: {
                title: "404",
                hide: true,
                needStoresysId: false,
              } as any,
              component: () => import("@/views/common/404.vue"),
            },
          ])
        );
        resolve("路由添加成功");
      });
    },
  },
});
